package com.green.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.green.entity.TbExcel;
import com.green.mapper.TbExcelMapper;
import com.green.service.TbExcelService;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author greenCai
 * @description 针对表【tb_excel】的数据库操作Service实现
 * @createDate 2024-11-17 13:34:58
 */
@Service
public class TbExcelServiceImpl extends ServiceImpl<TbExcelMapper, TbExcel> implements TbExcelService {

    @Override
    public void generateData() {
        List<TbExcel> list = new ArrayList<>();
        double min = -10;
        double max = 1000;
        for (int i = 0; i < 10000; i++) {
            double random = (max - min) * Math.random() + min;
            random = Math.round(random * 100.0) / 100.0;
            TbExcel tbExcel = new TbExcel();
            tbExcel.setDecCol(new java.math.BigDecimal(random));
            tbExcel.setStrCol("strCol" + i);
            tbExcel.setDateTimeCol(LocalDateTime.now());
            list.add(tbExcel);
        }
        this.saveBatch(list);

    }

    @Override
public void init() {
    LocalDateTime now = LocalDateTime.now();
    ExecutorService executor = Executors.newFixedThreadPool(10); // 调整线程池大小以适应更高的负载

    executor.execute(() -> {
        int batchSize = 1000; // 每次批量插入的数量
        double min = -10;
        double max = 1000;

        for (int i = 0; i < 1000000; i += batchSize) { // 循环插入一百万条数据
            List<TbExcel> list = new ArrayList<>(batchSize);
            for (int j = 0; j < batchSize; j++) {
                double random = (max - min) * Math.random() + min;
                random = Math.round(random * 100.0) / 100.0;
                TbExcel tbExcel = new TbExcel();
                tbExcel.setDecCol(new java.math.BigDecimal(random));
                tbExcel.setStrCol("strCol" + (i + j));
                tbExcel.setDateTimeCol(now);
                list.add(tbExcel);
            }
            Db.saveBatch(list); // 批量插入
        }
    });

    executor.shutdown();
}

}




